package com.lagou.edu;


import com.alibaba.dubbo.rpc.support.RpcUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.Map;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

    private static Integer count  = 0;
    private static Map<String, Long> timeMap90 = new HashMap<String, Long>();
    private static Map<String, Long> timeMap99 = new HashMap<String, Long>();
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {


        if(count == 0){
            synchronized (TPMonitorFilter.class){
                if(count == 0){
                    count++;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            count++;
                            printAll();
                        }
                    }).start();
                }

            }
        }


        long   startTime  = System.currentTimeMillis();
        try {
            // 执行方法
            return  invoker.invoke(invocation);
        } finally {
            boolean async = RpcUtils.isAsync(invoker.getUrl(), invocation);
            //判断是否是异步调用
            if(!async){
                long handleTime = System.currentTimeMillis()-startTime;
                String key = invoker.getInterface().getSimpleName()
                        + "=>" + invocation.getMethodName()+"=>startTime";
                if(handleTime>90){
                    timeMap90.put(key,handleTime);
                }
                if(handleTime>99){
                    timeMap99.put(key,handleTime);
                }
            }
        }

    }

    private  void printAll(){
        System.out.println("============================================90");
        for (Map.Entry<String, Long> entry : timeMap90.entrySet()) {
            System.out.println("timeMap90 Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        System.out.println("============================================99");

        for (Map.Entry<String, Long> entry : timeMap90.entrySet()) {

            System.out.println("timeMap90 Key = " + entry.getKey() + ", Value = " + entry.getValue());

        }
        System.out.println("============================================end");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        printAll();
    }
}
